package models

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/smash-llj/Nexa-server/global"
	"gorm.io/gorm"
)

// User 用户模型
type User struct {
	global.BaseModal
	UUID      string    `json:"uuid" gorm:"type:varchar(36);comment:用户id"`
	Username  string    `json:"username" gorm:"type:varchar(10);comment:用户名"`
	Password  string    `json:"-" gorm:"comment:密码"`
	Email     string    `json:"email" gorm:"type:varchar(36);comment:电子邮箱"`
	Avatar    string    `json:"avatar" gorm:"comment:用户头像;not null;default:https://i.pinimg.com/236x/24/f2/25/24f22516ec47facdc2dc114f8c3de7db.jpg"`
	Address   string    `json:"address" gorm:"comment:用户地址"`
	Phone     string    `json:"phone" gorm:"comment:电话"`
	Sign      string    `json:"sign" gorm:"not null;default:还没有设置个性签名;comment:个性签名"`
	Birthdate time.Time `json:"birthdate" gorm:"not null;default:CURRENT_TIMESTAMP;comment:出生日期"`
	Gender    string    `json:"gender" gorm:"type:enum('0','1','2');default:'0';comment:性别"`
	BgImage   string    `json:"bgImage" gorm:"not null;default:https://ik.imagekit.io/mpjl8xreo/treehole.png"`
}

// constraint:OnDelete:CASCADE;=>父级删除 子级也删除
// constraint: OnDelete:SET NULL;=> 父级删除 子级为Null

// 生成指定位数的随机数字字符串
func generateRandomDigits(length int) string {
	min := int64(1)
	for i := 1; i < length; i++ {
		min *= 10
	}
	max := min*10 - 1
	return strconv.FormatInt(rand.Int63n(max-min+1)+min, 10)
}

// 生成唯一ID：长度8~11的随机数字字符串 + 数据库去重
func generateUniqueNumericID(db *gorm.DB) (string, error) {
	for i := 0; i < 10; i++ { // 最多尝试10次
		length := rand.Intn(4) + 8 // 8~11
		candidate := generateRandomDigits(length)
		var count int64
		err := db.Model(&User{}).Where("uuid = ?", candidate).Count(&count).Error
		if err != nil {
			return "", err
		}
		if count == 0 {
			return candidate, nil
		}
	}
	return "", fmt.Errorf("无法生成唯一的 UUID")
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	uid, err := generateUniqueNumericID(tx)
	if err != nil {
		return err
	}
	u.UUID = uid
	return nil
}
